package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.page.PageResult;
import cn.wolfcode.crm.query.EmployeeQuery;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void saveOrUpdate(Employee employee) {
        if(employee.getId()!=null){
            //更新操作
            employeeMapper.deleteRelationWithRole(employee.getId());
            for (Role role : employee.getRoles()) {
                employeeMapper.saveRelationWithRole(employee.getId(),role.getId());
            }
            employeeMapper.updateByPrimaryKey(employee);
        }else {
            employee.setPassword("1");
            employee.setInputTime(new Date());
            employee.setState(Employee.NORMAL);
            employee.setAdmin(false);
            employeeMapper.insert(employee);
            for (Role role : employee.getRoles()) {
                employeeMapper.saveRelationWithRole(employee.getId(),role.getId());
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRelationWithRole(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageResult query(EmployeeQuery qo) {
        int count = employeeMapper.queryForCount(qo);
        PageResult pageResult = null;
        if(count == 0){
            pageResult = new PageResult(count, Collections.EMPTY_LIST);
        }
        List<Employee> list = employeeMapper.queryForList(qo);
        return new PageResult(count,list);
    }

    @Override
    public void updateState(Long id) {
        employeeMapper.updateState(id);
    }
}
